package com.putao.album.main.view;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.putao.album.util.DisplayHelper;
import com.putao.album.util.Loger;

import java.util.LinkedList;

/**
 * Created by jidongdong on 15/6/17.
 */
public class FlipImageViewLayout extends FrameLayout {
    private LinkedList<String> mImageUrls = new LinkedList<String>();
    private Context context;
    private OnRemoveListener onRemoveListener;

    public FlipImageViewLayout(Context context) {
        super(context);
        this.context = context;
    }

    public FlipImageViewLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    public FlipImageViewLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
    }

    public void setonRemoveListener(OnRemoveListener listener) {
        onRemoveListener = listener;
    }

    /**
     * 设置ImageURIs
     *
     * @param Urls
     */
    public void setImageUrls(String[] Urls) {
        if (Urls == null || Urls.length <= 0) {
            return;
        }
        this.mImageUrls.clear();
        removeAllViews();
        for (int i = 0; i < Urls.length; i++) {
            if (i < 3) {
                AddImageView(Urls[i]);
            } else {
                this.mImageUrls.add(Urls[i]);
            }
        }
    }

    /**
     * 添加View
     *
     * @param url
     */
    void AddImageView(String url) {
        if (!TextUtils.isEmpty(url)) {
            FlipRotateImageView view = new FlipRotateImageView(context);
            int w = (int) (DisplayHelper.getScreenWidth() * 4.0f / 5);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(w, w);
            params.gravity = Gravity.CENTER;
            params.topMargin = 10;
            view.setLayoutParams(params);
            view.setOnAnimationEndListener(getListener());
            ImageLoader.getInstance().displayImage(url, view);
            addView(view, 0);
        }
    }

    /**
     * 移除一个新增一个
     *
     * @return
     */
    private FlipRotateImageView.OnAnimationEndListener getListener() {
        return new FlipRotateImageView.OnAnimationEndListener() {
            @Override
            public void onAnimationEnd(View v) {
                removeView(v);
                String url = mImageUrls.poll();
                AddImageView(url);
                if (onRemoveListener != null) {
                    onRemoveListener.onRemoveEnd(getChildCount() + mImageUrls.size());
                }
            }
        };
    }

    /**
     * 提供剩余图片数目
     */
    public interface OnRemoveListener {
        void onRemoveEnd(int size);
    }

}
